package com.sync.hkmjsyncdata.task;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sync.hkmjsyncdata.config.isecurecenter.IsecureCenterUtilsService;
import com.sync.hkmjsyncdata.pojo.po.HkEventRecord;
import com.sync.hkmjsyncdata.pojo.po.HkEventVehicle;
import com.sync.hkmjsyncdata.service.IHkEventVehicleService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SyncMjEventVehicle {


    static final String PAGE_NO_KEY = "pageNo";
    static final String PAGE_SIZE_KEY = "pageSize";

    @Resource
    IsecureCenterUtilsService centerUtilsService;


    @Resource
    IHkEventVehicleService eventVehicleService;



    /**
     * 同步海康车辆
     */
    @XxlJob("SyncMjEventVehicle")
    public void SyncMjEventVehicleData() {
        XxlJobHelper.log("开始同步海康门禁车辆进出记录信息");
        LambdaQueryWrapper<HkEventVehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(HkEventVehicle::getEntranceDate).last(" limit 1");
        HkEventVehicle vehicle = eventVehicleService.getOne(queryWrapper, false);
        String bgDate = LocalDate.now().minusDays(7).toString();
        String receiveStartTime = convertDateTimeFormatto(bgDate + " 00:00:00");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (ObjectUtils.isNotEmpty(vehicle) && ObjectUtils.isNotEmpty(vehicle.getEntranceDate())) {
            receiveStartTime = convertDateTimeFormatto(vehicle.getEntranceDate().format(formatter));
        }
        String receiveEndTime = convertDateTimeFormatto(LocalDateTime.now().format(formatter));


        SyncMjEventRecordDataByHk(1, receiveStartTime, receiveEndTime);


    }

    private void SyncMjEventRecordDataByHk(int pageNo, String receiveStartTime, String receiveEndTime) {
        JSONObject recordParams = new JSONObject();
        recordParams.put(PAGE_NO_KEY, pageNo);
        recordParams.put(PAGE_SIZE_KEY, 1000);
        recordParams.put("startTime", receiveStartTime);
        recordParams.put("endTime", receiveEndTime);

        XxlJobHelper.log("同步海康门禁人员打卡记录查询条件：{}", recordParams.toJSONString());
        String resultInfo = centerUtilsService.doPost("/api/pms/v1/crossRecords/page", recordParams.toJSONString());
        XxlJobHelper.log("同步海康门禁人员打卡记录返回：{}", resultInfo);
        if (StringUtils.isNotBlank(resultInfo)) {
            JSONObject recordResult = JSON.parseObject(resultInfo);
            JSONObject recordData = recordResult.getJSONObject("data");
            if (ObjectUtils.isNotEmpty(recordData) && ObjectUtils.isNotEmpty(recordData.getJSONArray("list"))) {
                JSONArray list = recordData.getJSONArray("list");
                buildMjEventData(list);
                if (ObjectUtils.isNotEmpty(list)) {
                    SyncMjEventRecordDataByHk(pageNo + 1, receiveStartTime, receiveEndTime);
                }

            } else {
                XxlJobHelper.log("同步海康门禁人员打卡记录失败");
            }
        }


    }

    @Async
    protected void buildMjEventData(JSONArray list) {
        List<HkEventVehicle> eventList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject eventInfo = list.getJSONObject(i);
            eventList.add(new HkEventVehicle()
                    .setCphnbsht(eventInfo.getString("plateNo"))
                    .setMjdNam(eventInfo.getString("entranceName"))
                    .setMjdId(eventInfo.getString("entranceSyscode"))
                    .setRcclTyp(1)
                    .setEntranceType(1)
                    .setEntranceDate(parse(eventInfo.getString("crossTime").substring(0, 19)
                            .replaceAll("T", " "), "yyyy-MM-dd HH:mm:ss"))
                    .setEventId(eventInfo.getString("eventId"))
                    .setEntrance(convertInAndOutType(eventInfo.getInteger("vehicleOut")))
            );
        }
        XxlJobHelper.log("更新进场记录：{}",eventList.size());
        eventVehicleService.saveOrUpdateBatch(eventList);
    }
    public static LocalDateTime parse(String str, String format) {
        log.info("时间格式化:{}", str);
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(str, df);
    }
    private String convertInAndOutType(Integer inAndOutType) {
        if (inAndOutType == 0) {
            return "Y";
        } else if (inAndOutType == 1) {
            return "N";
        } else {
            return "未知";
        }
    }

    /**
     * 时间格式转换-DateTime转String参数
     *
     * @param sourceDateTimeString
     * @return
     */
    private String convertDateTimeFormatto(String sourceDateTimeString) {
        DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        // 解析源日期时间字符串为 LocalDateTime（没有关联时区）
        LocalDateTime localDateTime = LocalDateTime.parse(sourceDateTimeString, sourceFormatter);
        // 使用 ZoneId.of("Asia/Shanghai") 将 LocalDateTime 转换为带有时区的 ZonedDateTime 对象
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));
        // 格式化为指定的目标日期时间字符串格式
        String targetDateTimeString = zonedDateTime.format(targetFormatter);

        return targetDateTimeString;
    }








}
